//
// Created by keep on 17-10-6.
//

#include "com_service.h"
#include "uart.h"
#include "inc.h"
#include "config.h"

extern process_mgr_t process_mgr;
extern string g_server_addr;
extern string g_server_url;
extern string g_station_id;

long GetCurrentStamp64()
{
//    boost::posix_time::ptime epoch(boost::gregorian::date(1970, boost::gregorian::Jan, 1));
//    boost::posix_time::time_duration time_from_epoch = boost::posix_time::second_clock::universal_time() - epoch;
//    //return time_from_epoch.total_microseconds();
////    return time_from_epoch.total_milliseconds();
//    return time_from_epoch.total_seconds();
    struct timeval tv;
    gettimeofday(&tv,NULL);
//    printf("second:%ld\n",tv.tv_sec);  //秒
    long timestamp = tv.tv_sec*1000 + tv.tv_usec/1000;
//    printf("millisecond:%ld\n",timestamp);  //毫秒
    return  timestamp;
}

int handle_event_response(int pre_cond, string &decoded_data)
{
    int cmd_type = process_mgr->cmd_type;
    //parse the json reponse
    Json::Value root;
    Json::CharReaderBuilder rbuilder;
    Json::Value resp_default_data;
    std::string errs;
    istringstream in;
    in.str(decoded_data);

    string code;
    string desc;
    Json::Value resp_data;
    Json::Value com_resp_root;
    int ret = -1;
    do{
        if(cmd_type == 0xC4){
            //car white list response
            if(pre_cond != 0){
                com_resp_root["qryresult"] = 1;
                dzlog_error("Failed to request to the server");
                break;
            }
            try{
                bool parsingSuccessful = Json::parseFromStream(rbuilder, in, &root, &errs);
                if(!parsingSuccessful){
                    com_resp_root["qryresult"] = -1102;
                    dzlog_error("Failed to parse configuration");
                    break;
                }
                else{
                    code = root.get("code", "9999").asString();
                    desc = root.get("desc", "default").asString();
                    resp_data = root.get("data", resp_default_data);

                    if(strcmp(code.c_str(),"0000") == 0){
                        if(resp_data == resp_default_data){
                            com_resp_root["qryresult"] = 1;
                            break;
                        }
                        dzlog_debug("resp ok");
                        string order_id = resp_data.get("order_id","").asString();
                        string card_net_id = resp_data.get("card_net_id","").asString();
                        string card_type = resp_data.get("card_type","99").asString();
                        string card_id = resp_data.get("card_id","").asString();
                        int entry_station_id = resp_data.get("entry_station_id",99).asInt();
                        int enlane_type = resp_data.get("enlane_type",99).asInt();
                        int entry_lane_id = resp_data.get("entry_lane_id",99).asInt();
                        string en_time = resp_data.get("en_time","").asString();
                        int en_waste_sn = resp_data.get("en_waste_sn",99).asInt();
                        int en_oper = resp_data.get("en_oper",99).asInt();
                        string car_model = resp_data.get("car_model","").asString();
                        string car_type = resp_data.get("car_type","").asString();
                        string plate_no = resp_data.get("plate_no","").asString();
                        string plate_color = resp_data.get("plate_color","").asString();
                        string en_term_no = resp_data.get("en_term_no","").asString();
                        //这里改成intunsigned char nFlagCount;//标识站数,0表示无标识站
                        string flag_count = resp_data.get("flag_count","").asString();
                        //这里如果使用的话应该是int数组 unsigned char FlagInfo[10];//经过的标识站，最多10个
                        string flag_info = resp_data.get("flag_info","").asString();
                        string bak = resp_data.get("bak","").asString();
                        //convert to zhe com proto
                        //ok
                        com_resp_root["qryresult"] = 0;
                        com_resp_root["orderid"] = (unsigned)strtol(order_id.c_str(), nullptr, 10);//int
                        com_resp_root["cardnetid"] = card_net_id;//string
                        com_resp_root["cardtype"] = (int)strtol(card_type.c_str(), nullptr, 10);//int
                        com_resp_root["cardid"] = card_id;      //string
                        com_resp_root["entrystationid"] = entry_station_id;     //int
                        com_resp_root["enlanetype"] = enlane_type;      //int
                        com_resp_root["entrylaneid"] = entry_lane_id;   //int
                        com_resp_root["entime"] = en_time;
                        com_resp_root["enwastesn"] = en_waste_sn;   //int
                        com_resp_root["enoper"] = en_oper;//int
                        com_resp_root["envc"] = (int)strtol(car_model.c_str(), nullptr, 10);//int;
                        com_resp_root["envt"] = (int)strtol(car_type.c_str(), nullptr, 10);//int;
                        com_resp_root["envlp"] = boost::locale::conv::between(plate_no, "GBK", "UTF-8" ); //string
                        com_resp_root["envlpc"] = (int)strtol(plate_color.c_str(), nullptr, 10);//int;;
                        com_resp_root["entermno"] = en_term_no;
                        com_resp_root["flagcount"] = (int)strtol(flag_count.c_str(), nullptr, 10);//int;;;
                        com_resp_root["flaginfo"] = flag_info;
                        com_resp_root["bak"] = bak;
                    }else if(strcmp(code.c_str(),"1003") == 0){
                        dzlog_error("the car is no in white list");
                        com_resp_root["qryresult"] = 2;
                    }else if(strcmp(code.c_str(),"4001") == 0){
                        dzlog_error("not found the car enter info");
                        com_resp_root["qryresult"] = 2;
                    }else{
                        dzlog_error("resp error:%s", code.c_str());
                        com_resp_root["qryresult"] = (int)strtol(code.c_str(), NULL, 10);
                    }
                }

            }catch (Json::Exception &exception){
                dzlog_error("json error:%s", exception.what());
                ret = -1106;
                com_resp_root["qryresult"] = ret;
            }catch (...){
                ret = -1107;
                com_resp_root["qryresult"] = ret;
            }

        }else if(cmd_type == 0xC5 || cmd_type == 0xC6){
            //car white list response
            if(pre_cond != 0){
                com_resp_root["transresult"] = 1;
                com_resp_root["unionpayinfo"] = "request to server error";
                dzlog_error("Failed to request to the server");
                break;
            }
            try{
                bool parsingSuccessful = Json::parseFromStream(rbuilder, in, &root, &errs);
                if(!parsingSuccessful){
                    com_resp_root["transresult"] = -1102;
                    com_resp_root["unionpayinfo"] = "parse resp failed";
                    dzlog_error("Failed to parse configurationz");
                    break;
                }
                else{
                    code = root.get("code", "9999").asString();
                    desc = root.get("desc", "default").asString();
                    resp_data = root.get("data", resp_default_data);

                    if(strcmp(code.c_str(),"0000") == 0){
                        if(resp_data == resp_default_data){
                            com_resp_root["transresult"] = 1;
                            com_resp_root["unionpayinfo"] = "resp data is null";
                            break;
                        }
                        dzlog_debug("resp ok");
                        string order_id = resp_data.get("order_id","").asString();
                        int trans_result = resp_data.get("trans_result",99).asInt();
                        int trans_type = resp_data.get("trans_type",99).asInt();
                        int balance = resp_data.get("balance",0).asInt();
                        string union_pay_info = resp_data.get("union_pay_info","").asString();

                        //convert to zhe com proto
                        //ok
                        com_resp_root["transresult"] = trans_result;
                        com_resp_root["orderid"] = (unsigned)strtol(order_id.c_str(), nullptr, 10);//int
                        com_resp_root["transtype"] = trans_type;
                        com_resp_root["balance"] = balance;//int
                        //TODO GBK
                        com_resp_root["unionpayinfo"] = union_pay_info;      //string
                    }else{
                        dzlog_error("%02X resp error:%s", cmd_type, code.c_str());
                        com_resp_root["transresult"] = (int)strtol(code.c_str(), NULL, 10);
                        com_resp_root["unionpayinfo"] = "resp error:"+code;
                    }
                }

            }catch (Json::Exception &exception){
                dzlog_error("json error:%s", exception.what());
                ret = -1106;
                com_resp_root["transresult"] = ret;
                com_resp_root["unionpayinfo"] = "json error:";
            }catch (...){
                ret = -1107;
                com_resp_root["transresult"] = ret;
                com_resp_root["unionpayinfo"] = "unknown exception";
            }
        }else if(cmd_type == 0xC8){
            //will never to be here!!
            com_resp_root["comstate"] = 0;
            com_resp_root["netstate"] = 0;//int
        } else{
            dzlog_error("error cmd %02X\n", cmd_type);
            ret = -1105;
            return ret;
        }
    }while(false);

    Json::StreamWriterBuilder builder;
    builder.settings_["indentation"] = "";
    std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());

    ostringstream out_json;
    writer->write(com_resp_root, &out_json);
    string str_out_json = out_json.str();
    dzlog_debug("resp root json:%s", str_out_json.c_str());
    char ch_cmd_type[3] = {0};
    sprintf(ch_cmd_type, "%02X", cmd_type);
    string str_cmd_type = ch_cmd_type;
    string resp_header = "BF0801"+str_cmd_type;
    ssize_t idata_length = str_out_json.length();
    char tmp[5] = {0};
    sprintf(tmp, "%04X", idata_length);
    string data_length = tmp;
    string resp_end_data = resp_header + data_length + str_out_json;
    dzlog_info("<<< resp com data :");
    dzlog_info("%s",resp_end_data.c_str());
    ssize_t n = resp_end_data.length();
    if(process_mgr->com_fd > 0){
        ssize_t nwrite = writen(process_mgr->com_fd, resp_end_data.c_str(), n);
        if(nwrite < n){
            dzlog_error("write to the com failed(%ld--%ld)", n, nwrite);
            ret = -1;
        }else{
            ret = 0;
        }
    }else{
        dzlog_error("error fd");
    }

    dzlog_info("CMD [%02X] DONE... ...\n\n", cmd_type);

    return ret;

}
//这是libcurl接收数据的回调函数，相当于recv的死循环
//其中stream可以自定义数据类型，这里我传入的是文件保存路径

static size_t write_callback(void *ptr, size_t size, size_t nmemb, void *stream) {

    int len = size * nmemb;
    int written = len;

    string output_str;
    Base64Decode((const char*)ptr, &output_str);

    dzlog_info("decode resp:\n");
    dzlog_info(output_str.c_str());

    handle_event_response(0, output_str);
    return written;
}

int http_request(string & params)
{
    CURL *pCurl = nullptr;
    try
    {
        CURLcode res;
        // get a curl handle
        pCurl = curl_easy_init();
        if (pCurl != nullptr){
            // 设置http发送的内容类型为JSON
//            curl_slist *plist = curl_slist_append(NULL, "Content-Type:application/json;charset=UTF-8");
//            curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);
//            printf("send:%s\n", szJsonData);
            // 设置要POST的JSON数据
//            curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, szJsonData);
            curl_easy_setopt(pCurl, CURLOPT_NOSIGNAL,1L);
            curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 3);//单位 秒
//            char server_url[64] = {0};
//            sprintf(server_url,"http://%s/iETC/ipc/trans", g_server_addr.c_str());
            dzlog_info("request url : %s", g_server_url.c_str());
            curl_easy_setopt(pCurl, CURLOPT_URL, g_server_url.c_str());
            curl_httppost *post = nullptr;
            curl_httppost *last = nullptr;
            curl_formadd(&post, &last, CURLFORM_COPYNAME, "message", CURLFORM_COPYCONTENTS, params.c_str(), CURLFORM_END);
            curl_easy_setopt(pCurl, CURLOPT_HTTPPOST, post);
            curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, write_callback);
            // Perform the request, res will get the return code
            res = curl_easy_perform(pCurl);
            dzlog_info("http request end\n");
            //Free a multipart formpost previously built with curl_formadd()
            curl_formfree(post);
            // Check for errors
            if (res != CURLE_OK)
            {
                dzlog_error("curl_easy_perform() failed:%s", curl_easy_strerror(res));
                // always cleanup
                curl_easy_cleanup(pCurl);
                return -1;
            }else{
                dzlog_debug("curl_easy_perform() ok");
                // always cleanup
                curl_easy_cleanup(pCurl);
                return 0;
            }

        }else{
            dzlog_error("the curl ptr is null");
            return -1;
        }
    }
    catch (std::exception &ex)
    {
        dzlog_error("curl exception %s", ex.what());
        if (pCurl != nullptr){
            // always cleanup
            curl_easy_cleanup(pCurl);
        }
        return -1;
    }
}
int init(string & data)
{
    string resp_data;
    dzlog_info("init local params ok:%s",data.c_str());
    int ret = update_config_all(data);
    if(ret != 0){
        dzlog_error("init config file error:%d", ret);
        resp_data = "BF0801C100011";
    }else{
        dzlog_info("update config file success, to init again");
        bool bret = init_config();
        if(bret){
            dzlog_info("init config file success");
            resp_data = "BF0801C100010";
        }else{
            dzlog_error("reinit config file failed");
            resp_data = "BF0801C100012";
        }

    }

    dzlog_info("init resp data(%ld):%s", resp_data.length(), resp_data.c_str());
    ssize_t n = resp_data.length();
    if(process_mgr->com_fd > 0){
        ssize_t nwrite = writen(process_mgr->com_fd, resp_data.c_str(), n);
        if(nwrite < n){
            dzlog_error("write to the com failed(%ld--%ld)", n, nwrite);
            return -1;
        }else{
            return 0;
        }
    }else{
        dzlog_error("init write error fd");
        return -2;
    }
}
int query_car_order_info(int fd, string & data)
{
    int ret = -1;
    do{
        try
        {
//            dzlog_debug("query_car_order_info recv data:\n%s\n", data.c_str());
            Json::Value root;
            Json::CharReaderBuilder rbuilder;
            std::string errs;
            istringstream in;
            in.str(data);
            bool parsingSuccessful = Json::parseFromStream(rbuilder, in, &root, &errs);
            if (!parsingSuccessful)
            {
                // report to the user the failure and their locations in the document.
                dzlog_error("Failed to parse configuration");
                ret = -1101;
                break;
            }
            else
            {
                int stationid = root.get("stationid", 2222).asInt();
                int lanetype = root.get("lanetype", 1).asInt();
                int laneid = root.get("laneid", 1).asInt();
                string vlp = root.get("vlp","").asString();
                int vlpc = root.get("vlpc", 99).asInt();
                int vc = root.get("vc", 99).asInt();
                int vt = root.get("vt", 99).asInt();
                int axlenum = root.get("axlenum", 99).asInt();
                int totalweight = root.get("totalweight", 99).asInt();
                int limitweight = root.get("limitweight", 99).asInt();


                Json::Value netReqRoot;
                //"{\"version\":1,\"biz_id\":\"ietc.itc.whitelist\",\"waste_sn\":\"1506594484515\",\"params\":{\"station_id\":1111,
                // \"lane_type\":3,\"lane_id\":3333,\"plate_no\":\"鲁A66889\",\"plate_color\":\"0\",\"car_model\":\"5\",\"car_type\":\"6\",
                // \"axle_num\":7777,\"total_weight\":8888,\"limit_weight\":9999}}";
                netReqRoot["version"] = 1;
                netReqRoot["biz_id"] = "ietc.itc.whitelist";
                string timestamp = to_string(GetCurrentStamp64());
//                printf("timestamp:%s\n", timestamp.c_str());
                netReqRoot["waste_sn"] = "C4"+g_station_id+timestamp;

                Json::Value netReqParams;
                netReqParams["station_id"] = stationid;
                netReqParams["lane_type"] = lanetype;
                netReqParams["lane_id"] = laneid;

                netReqParams["plate_no"] = boost::locale::conv::between(vlp, "UTF-8", "GBK" );
                netReqParams["plate_color"] = to_string(vlpc);
                netReqParams["car_model"] = to_string(vc);
                netReqParams["car_type"] = to_string(vt);
                netReqParams["axle_num"] = axlenum;
                netReqParams["total_weight"] = totalweight;
                netReqParams["limit_weight"] = limitweight;

                netReqRoot["params"] = netReqParams;

                Json::StreamWriterBuilder builder;
                builder.settings_["indentation"] = "";
                std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());

                ostringstream out_json;
                writer->write(netReqRoot, &out_json);
                string str_out_json = out_json.str();
                dzlog_info("C4 req json:%s\n", str_out_json.c_str());

                ret = http_request(str_out_json);

            }

        }catch (std::out_of_range &e) {
            dzlog_error("out of range:%s", e.what());
            ret = -1105;
        }catch (Json::Exception &exception1){
            dzlog_error("json error:%s", exception1.what());
            ret = -1106;
        }catch (...){
            ret = -1107;
        }
    }while(false);
    if(ret != 0){
        //只有ret不为0才处理，防止重复处理
//        dzlog_debug("must to do..");
        string default_data = "";
        handle_event_response(-1, default_data);
    }
    return ret;
}

int pos_trans(string & data)
{
    int ret = -1;
    do{
        try
        {
//            dzlog_debug(">>> pos_trans recv data:");
//            dzlog_debug("%s", data.c_str());
            Json::Value root;
            Json::CharReaderBuilder rbuilder;
            std::string errs;
            istringstream in;
            in.str(data);
            bool parsingSuccessful = Json::parseFromStream(rbuilder, in, &root, &errs);
            if (!parsingSuccessful)
            {
                // report to the user the failure and their locations in the document.
                dzlog_error("Failed to parse configuration");
                ret = -1101;
                break;
            }
            else
            {
                int orderid = root.get("orderid", 99).asInt();//订单号，通过查询返回的
                int transtype = root.get("transtype", 99).asInt();//交易类型 1-移动支付 2-扫码 3-银行卡
                int lastmoney = root.get("lastmoney", 99).asInt();//本次支付通行费，单位分
                int lastcardmoney = root.get("lastcardmoney", 99).asInt();//本次支付卡成本
                int stationid = root.get("stationid", 99).asInt();
                int lanetype = root.get("lanetype", 99).asInt();
                int laneid = root.get("laneid", 99).asInt();
                int wastsn = root.get("wastsn", 99).asInt();
                int vc = root.get("vc", 99).asInt();
                int vt = root.get("vt", 99).asInt();

                string vlp = root.get("vlp", 99).asString();
                int vlpcolor = root.get("vlpcolor", 99).asInt();
                string transtime = root.get("transtime", "").asString();
                string ldate = root.get("ldate", "").asString();
                string termno = root.get("termno", "").asString();
                string cardnetid = root.get("cardnetid", "").asString();
                string cardid = root.get("cardid", "").asString();
                int cardtype = root.get("cardtype", 99).asInt();
                int operid = root.get("operid", 99).asInt();
                int axlenum = root.get("axlenum", 99).asInt();
                int totalweight = root.get("totalweight", 99).asInt();
                int limitweight = root.get("limitweight", 99).asInt();
                int overweightrate = root.get("overweightrate", 99).asInt();
                int payrebate = root.get("payrebate", 99).asInt();
                int overtime = root.get("overtime", 99).asInt();
                int tollinstance = root.get("tollinstance", 99).asInt();
                int tollflag = root.get("tollflag", 99).asInt();
                string bak = root.get("bak", 99).asString();

                Json::Value defaultValue;
                Json::Value order_info_obj = root.get("orderinfo", defaultValue);
                if(order_info_obj == defaultValue){
                    dzlog_debug("there is no key \"orderinfo\"");
                }else{
                    dzlog_debug("there is key \"orderinfo\", but not uesed");
                }

                Json::Value netReqRoot;
                //"{\"version\":1,\"biz_id\":\"ietc.itc.whitelist\",\"waste_sn\":\"1506594484515\",\"params\":{\"station_id\":1111,
                // \"lane_type\":3,\"lane_id\":3333,\"plate_no\":\"鲁A66889\",\"plate_color\":\"0\",\"car_model\":\"5\",\"car_type\":\"6\",
                // \"axle_num\":7777,\"total_weight\":8888,\"limit_weight\":9999}}";
                netReqRoot["version"] = 1;
                string timestamp = to_string(GetCurrentStamp64());
                if(process_mgr->cmd_type == 0xC5){
                    netReqRoot["biz_id"] = "ietc.itc.trans";
                    netReqRoot["waste_sn"] = "C5"+g_station_id+timestamp;
                }else if(process_mgr->cmd_type == 0xC6){
                    netReqRoot["biz_id"] = "ietc.itc.trans.query";
                    netReqRoot["waste_sn"] = "C6"+g_station_id+timestamp;
                }
                netReqRoot["biz_id"] = "ietc.itc.trans";

                Json::Value netReqParams;
                netReqParams["order_id"] = to_string(orderid);
                netReqParams["trans_type"] = transtype;
                netReqParams["last_money"] = lastmoney;
                netReqParams["last_card_money"] = lastcardmoney;
                netReqParams["station_id"] = stationid;
                netReqParams["lane_type"] = lanetype;
                netReqParams["lane_id"] = laneid;
                netReqParams["wast_sn"] = wastsn;


                netReqParams["plate_no"] = boost::locale::conv::between(vlp, "UTF-8", "GBK" );
                netReqParams["plate_color"] = to_string(vlpcolor);
                netReqParams["car_model"] = to_string(vc);
                netReqParams["car_type"] = to_string(vt);

                netReqParams["trans_time"] = transtime;
                netReqParams["logic_date"] = ldate;
                netReqParams["term_no"] = termno;

                netReqParams["card_net_id"] = cardnetid;
                netReqParams["card_type"] = to_string(cardtype);
                netReqParams["card_id"] = cardid;
                netReqParams["oper_id"] = operid;

                netReqParams["axle_num"] = axlenum;
                netReqParams["total_weight"] = totalweight;
                netReqParams["limit_weight"] = limitweight;


                netReqParams["over_weight_rate"] = overweightrate;
                netReqParams["pay_rebate"] = payrebate;
                netReqParams["over_time"] = overtime;

                netReqParams["toll_instance"] = tollinstance;
                netReqParams["toll_flag"] = tollflag;
                netReqParams["entry_info"] = defaultValue;

                netReqRoot["params"] = netReqParams;

                Json::StreamWriterBuilder builder;
                builder.settings_["indentation"] = "";
                std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());

                ostringstream out_json;
                writer->write(netReqRoot, &out_json);
                string str_out_json = out_json.str();
                dzlog_info("req json:%s\n", str_out_json.c_str());

                ret = http_request(str_out_json);
            }

        }catch (std::out_of_range &e) {
            dzlog_error("out of range:%s", e.what());
            ret = -1105;
            break;
        }catch (Json::Exception &exception1){
            dzlog_error("json error:%s", exception1.what());
            ret = -1106;
            break;
        }catch (...){
            ret = -1107;
            break;
        }
    }while(false);
    if(ret != 0){
        //只有ret不为0才处理，防止重复处理
//        dzlog_debug("must to do..");
        string default_data = "";
        handle_event_response(-1, default_data);
    }
    return ret;
}

int get_pos_version(string & data)
{
    int ret = -1;
    string str_out_json = "{\"posinfo\":\"Linux\",\"posversion\":\"V1.0.7\"}";
    dzlog_debug("resp root json:%s", str_out_json.c_str());

    string resp_header = "BF0801C3";
    ssize_t idata_length = str_out_json.length();
    char tmp[5] = {0};
    sprintf(tmp, "%04X", idata_length);
    string data_length = tmp;
    string resp_end_data = resp_header + data_length + str_out_json;
    dzlog_info("<<< C3 resp data(%ld):%s", resp_end_data.length(), resp_end_data.c_str());
    ssize_t n = resp_end_data.length();
    if(process_mgr->com_fd > 0){
        ssize_t nwrite = writen(process_mgr->com_fd, resp_end_data.c_str(), n);
        if(nwrite < n){
            dzlog_error("write to the com failed(%ld--%ld)", n, nwrite);
            ret = -1;
        }else{
            ret = 0;
        }
    }else{
        dzlog_error("error fd");
    }
    return ret;

}
int get_pos_status(string & data)
{
    int ret = -1;
    string str_out_json = "{\"comstate\":0,\"netstate\":0}";
    dzlog_debug("resp root json:%s", str_out_json.c_str());

    string resp_header = "BF0801C8";
    ssize_t idata_length = str_out_json.length();
    char tmp[5] = {0};
    sprintf(tmp, "%04X", idata_length);
    string data_length = tmp;
    string resp_end_data = resp_header + data_length + str_out_json;
    dzlog_info("<<< C8 resp data(%ld):%s", resp_end_data.length(), resp_end_data.c_str());
    ssize_t n = resp_end_data.length();
    if(process_mgr->com_fd > 0){
        ssize_t nwrite = writen(process_mgr->com_fd, resp_end_data.c_str(), n);
        if(nwrite < n){
            dzlog_error("write to the com failed(%ld--%ld)", n, nwrite);
            ret = -1;
        }else{
            ret = 0;
        }
    }else{
        dzlog_error("error fd");
    }
    return ret;
}